package org.bdware.repository;

import com.google.gson.Gson;
import org.apache.log4j.Logger;
import org.bdware.doip.core.utils.GlobalConfigurations;

import java.io.*;

public class DoipServiceConfig {

    static Logger logger = Logger.getLogger(DoipServiceConfig.class);

    public String IRSAddress;
    public String userID;
    public String jwkPath;
    public String jksPath;
    public String jksPassword;
    public String repoID;
    public String listeners;
    public String serviceDescription;
    public String serviceName;
    public String type;
    public String repoPath;
    public String indexPath;

    public static DoipServiceConfig loadFromConfigFile(String filePath){
        logger.info("try to load config from: " + filePath);
        try{
            String configJson = readFile(filePath);
            return new Gson().fromJson(configJson, DoipServiceConfig.class);
        }catch (Exception e){
//            e.printStackTrace();
            return null;
        }
    }

    private static String readFile(String path) throws Exception{
        File file = new File(path);
        logger.debug("conf file absolute path: "+file.getAbsolutePath());
        StringBuilder configJson = new StringBuilder();
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line = br.readLine();
        while(line != null){
            configJson.append(line);
            line = br.readLine();
        }
        br.close();
        return configJson.toString();
    }

    public void save(String filePath) throws IOException {
        File f = new File(filePath);
        logger.info("config file path: " + f.getAbsolutePath());
        FileWriter fw = new FileWriter(f);
        fw.write(new Gson().toJson(this));
        fw.flush();
    }

    public static DoipServiceConfig createDefaultConfig(){

        /**
         * Default DOIP Service Information
         */
        String listeners = "[{\"url\":\"tcp://127.0.0.1:1717\",\"protocolVersion\":\"2.1\",\"messageFormat\":\"packet\"}]";
        String repoID = "unregistered";
        String serviceDescription = "Local BDRepository";
        String serviceName = "LocalBDRepo";
        String type = "repository";

        DoipServiceConfig doipServiceConfig = new DoipServiceConfig();

        //doip Service config
        doipServiceConfig.serviceDescription = serviceDescription;
        doipServiceConfig.serviceName = serviceName;
        doipServiceConfig.listeners = listeners;
        doipServiceConfig.repoID = repoID;
        doipServiceConfig.type = type;
        doipServiceConfig.userID = GlobalConfigurations.userID;
        //LHS config
        doipServiceConfig.IRSAddress = GlobalConfigurations.IRSAddress;

        //jwk config
        doipServiceConfig.jwkPath = GlobalConfigurations.JWKPath;

        doipServiceConfig.repoPath = "./repository/rocksdb/";
        doipServiceConfig.indexPath = "./repository/doIndex/";

        return doipServiceConfig;
    }

}
